from flask import Flask
from flask_mysqldb import MySQL
from flask_cors import CORS

# 初始化扩展对象（不依赖app实例）
mysql = MySQL()

def create_app(config_class='config.Config'):
    """
    应用工厂函数 - 优化版
    :param config_class: 配置类路径，默认为 config.Config
    :return: 配置完成的Flask应用实例
    """
    app = Flask(__name__)
    
    # 1. 加载配置（新增配置验证）
    app.config.from_object(config_class)
    validate_config(app.config)
    
    # 2. 初始化扩展（带错误处理）
    try:
        mysql.init_app(app)
        # 测试数据库连接
        with app.app_context():
            mysql.connection.ping(True)
    except Exception as e:
        raise RuntimeError(f"数据库初始化失败: {str(e)}")
    
    # 3. 配置CORS（更安全的默认设置）
    CORS(app, resources={r"/*": {"origins": "*"}})

    # 4. 注册蓝图
    register_blueprints_safely(app)
    
    # 设置MySQL游标类型为字典
    app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
    
    print(app.config['MYSQL_HOST'])
    print(app.url_map)
    
    return app

def validate_config(config):
    """验证必要配置项"""
    required_keys = [
        'MYSQL_HOST', 'MYSQL_USER', 
        'MYSQL_PASSWORD', 'MYSQL_DB'
    ]
    for key in required_keys:
        if not config.get(key):
            raise ValueError(f"缺少必要配置项: {key}")

from app.auth import auth_bp
def register_blueprints_safely(app):
    """安全注册蓝图（带错误隔离）"""
    blueprints = [
        ('auth', '/api'),
        ('routes', ''),
        ('video', '/api')
    ]
    import importlib 
    for module_name, url_prefix in blueprints:
        try:
            module = importlib.import_module(f'app.{module_name}')
            bp = getattr(module, f'{module_name}_bp')
            app.register_blueprint(bp, url_prefix=url_prefix)
        except Exception as e:
            app.logger.error(f"注册蓝图 {module_name} 失败: {str(e)}")
            if app.debug:
                raise

# 注册时用 url_prefix='/api'
